package com.work.tqyb.ui.activity;

import android.app.Activity;
import android.content.Intent;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.lifecycle.ViewModelProvider;

import com.work.tqyb.vm.WeatherVM;
import com.work.tqyb.base.BaseActivity;
import com.work.tqyb.databinding.ActivityWeatherInfoBinding;
import com.work.tqyb.http.response.CityListResponse;
import com.work.tqyb.ui.adapter.FutureAdapter;

public class WeatherInfoActivity extends BaseActivity {
    private WeatherVM vm;
    private ActivityWeatherInfoBinding binding;
    private FutureAdapter adapter;

    private ActivityResultLauncher<Intent> getCity = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), info -> {
        if (info.getResultCode() == Activity.RESULT_OK) {
            CityListResponse.CityBean cityBean = (CityListResponse.CityBean) info.getData().getSerializableExtra("city");
            vm.choiceCity = cityBean;
            vm.simpleWeatherQuery();
        }
    });

    @Override
    public void initData() {
        adapter = new FutureAdapter();
        vm = new ViewModelProvider(this).get(WeatherVM.class);
        binding = ActivityWeatherInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.lv.setAdapter(adapter);
        vm.setChoiceCity(new CityListResponse.CityBean("75", "黑龙江", "哈尔滨", "哈尔滨"));
        vm.simpleWeatherQuery();

    }

    @Override
    public void onViewClick() {
        binding.ibnBack.setOnClickListener(v -> finish());
        binding.ibnAdd.setOnClickListener(v -> getCity.launch(new Intent(WeatherInfoActivity.this, CityListActivity.class)));
        binding.btn.setOnClickListener(v -> {
            if (adapter.futureArrayList == null) return;
            if (adapter.futureArrayList.isEmpty()) return;
            Intent intent = new Intent(WeatherInfoActivity.this, LookFiveDayActivity.class);
            intent.putExtra("city", vm.choiceCity.city);
            intent.putExtra("five", adapter.futureArrayList);
            startActivity(intent);
        });

    }

    @Override
    public void observe() {
        vm.getQueryLD().observe(this, queryInfo -> {
            binding.city.setText("城市:" + queryInfo.city);
            binding.tvInfo.setText("信息:" + queryInfo.realtime.temperature + "°   " + queryInfo.realtime.info);
            binding.directPower.setText("风向:" + queryInfo.realtime.direct + "   " + queryInfo.realtime.power);
            binding.tvHumidity.setText("湿度:" + queryInfo.realtime.humidity + "°   ");
            adapter.futureArrayList = queryInfo.future;
            adapter.notifyDataSetChanged();
        });
    }
}
